package com.mihuo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mihuo.compoent.RedisUtil;
import com.mihuo.entity.AppUser;
import com.mihuo.entity.common.AuthUser;
import com.mihuo.entity.constant.Constant;
import com.mihuo.entity.constant.RedisKey;
import com.mihuo.entity.dto.AccountLoginDTO;
import com.mihuo.entity.exception.BaseException;
import com.mihuo.mapper.AppUserMapper;
import com.mihuo.service.IAppUserService;
import com.mihuo.util.JwtUtil;
import com.mihuo.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public String accountLogin(AccountLoginDTO dto) {
        AppUser user = lambdaQuery().eq(AppUser::getAccount, dto.getAccount()).one();
        if (user == null) {
            throw new BaseException("查不到用户");
        }
        String password = MD5Util.md5(dto.getPassword());
        if(!password.equals(user.getPassword())) {
            throw new BaseException("密码不正确");
        }

        String token = JwtUtil.createToken(user.getId().toString(), Arrays.asList(Constant.ROLE_NORMAL));
        redisUtil.set(RedisKey.LOGIN_USER + token,new AuthUser(user), RedisKey.LOGIN_USER_EXPIRE);
        return token;
    }
}
